package sing.core.util

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.text.style.ImageSpan
import android.view.View
import android.widget.TextView
import sing.core.ext.view.clickNoRepeat

/**
 * @ProjectName: shanqian
 * @Package: com.gengguang.lib_common.utils
 * @ClassName: TextUtils
 * @Description: 登录协议处理
 * @Author: 张岩
 * @CreateDate: 2021/1/4 下午4:48
 */
object AgreementTextUtils {
    val builder: Builder
        get() = Builder()

    private fun setImageSpan(context: Context, builder: SpannableStringBuilder, resourceId: Int) {
        val imageSpan = MyImageSpan(context, resourceId, 2) //居中对齐
        builder.setSpan(imageSpan, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
    }

    class Builder() {
        private val strBuilder: SpannableStringBuilder = SpannableStringBuilder()
        fun append(text: CharSequence?): Builder {
            strBuilder.append(text)
            return this
        }

        fun append(text: CharSequence?, color: Int): Builder {
            val start = strBuilder.length
            strBuilder.append(text)
            val end = strBuilder.length
            strBuilder.setSpan(
                ForegroundColorSpan(color),
                start,
                end,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )
            return this
        }

        fun replace(text: CharSequence, color: Int, vararg replaces: String): Builder {
            strBuilder.append(text)
            for (i in 0 until replaces.size) {
                val replace = replaces[i]
                val start = text.toString().indexOf(replace)
                if (start >= 0) {
                    val end = start + replace.length
                    strBuilder.setSpan(
                        ForegroundColorSpan(color),
                        start,
                        end,
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                    )
                }
            }
            return this
        }

        fun click(text: CharSequence, color: Int = Color.parseColor("#0ec352"), onClickListener: OnClickListener?, vararg clickTexts: String?): Builder {
            strBuilder.append(text)
            for (i in clickTexts.indices) {
                val clickText = clickTexts[i]
                val start = text.toString().indexOf(clickText!!)
                if (start >= 0) {
                    val end = start + clickText!!.length
                    strBuilder.setSpan(object : ClickableSpan() {
                        override fun onClick(view: View) {
                            view.clickNoRepeat { onClickListener?.onClick(i) }
                        }

                        override fun updateDrawState(ds: TextPaint) {
                            super.updateDrawState(ds)
                            ds.color = color
                            ds.isUnderlineText = false
                            ds.isFakeBoldText = true
                        }
                    }, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
                }
            }
            return this
        }

        private val isChecked = false

        //设置复选框 因为该方法没有调strBuilder.append()，故请务必在调用该方法前保证strBuilder不为空，即调用了前面的方法
        fun checkBox(context: Context?, tv: TextView?, listener: OnImageClickListener?): Builder {
//            setImageSpan(context, strBuilder, R.drawable.xzhhr_icon_circle2x);
            strBuilder.setSpan(object : ClickableSpan() {
                override fun onClick(view: View) {
//                    isChecked = !isChecked;
//                    if (isChecked){
//                        setImageSpan(context, strBuilder, R.drawable.xzhhr_icon_tick2x);
//                        tv.setText(strBuilder);//刷新显示
//                        listener.onChecked();
//                    } else {
//                        setImageSpan(context, strBuilder, R.drawable.xzhhr_icon_circle2x);
//                        tv.setText(strBuilder);
//                        listener.onUnChecked();
//                    }
                }

                override fun updateDrawState(ds: TextPaint) {
                    super.updateDrawState(ds)
                    ds.color = Color.WHITE
                    ds.isUnderlineText = false
                }
            }, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            return this
        }

        fun clickInto(tv: TextView): Builder {
            tv.movementMethod = LinkMovementMethod.getInstance() //设置可点击状态
            tv.highlightColor = Color.TRANSPARENT //设置点击后的颜色为透明
            tv.text = strBuilder
            return this
        }

        fun into(tv: TextView): Builder {
            tv.text = strBuilder
            return this
        }

    }

    interface OnClickListener {
        fun onClick(position: Int)
    }

    interface OnImageClickListener {
        fun onChecked()
        fun onUnChecked()
    }

    class MyImageSpan  //因为这里文字存在换行,系统的ImageSpan图标无法进行居中，所以我们自定义一个ImageSpan,重写draw方法,解决了该问题
        (context: Context, resourceId: Int, verticalAlignment: Int) :
        ImageSpan(context, resourceId, verticalAlignment) {
        override fun draw(
            canvas: Canvas,
            text: CharSequence,
            start: Int,
            end: Int,
            x: Float,
            top: Int,
            y: Int,
            bottom: Int,
            paint: Paint
        ) {
            val drawable = drawable
            canvas.save()
            //获取画笔的文字绘制时的具体测量数据
            val fm = paint.fontMetricsInt
            var transY = bottom - drawable.bounds.bottom
            if (mVerticalAlignment == ALIGN_BASELINE) {
                transY -= fm.descent
            } else if (mVerticalAlignment == ALIGN_CENTER) { //自定义居中对齐
                //与文字的中间线对齐（这种方式不论是否设置行间距都能保障文字的中间线和图片的中间线是对齐的）
                // y+ascent得到文字内容的顶部坐标，y+descent得到文字的底部坐标，（顶部坐标+底部坐标）/2=文字内容中间线坐标
                transY = (y + fm.descent + (y + fm.ascent)) / 2 - drawable.bounds.bottom / 2
            }
            canvas.translate(x, transY.toFloat())
            drawable.draw(canvas)
            canvas.restore()
        }
    }
}